<?php
/**
 * Created by PhpStorm.
 * User: godjarvis
 * Date: 2020/08/06
 * Time: 09:36
 */

namespace App\Model\Dao\DangKou;

use App\Model\Entity\DangKou\ApiHupunTrades;
use App\Model\Entity\DangKou\Client;
use Fresh\Annotation\ConnectionField;
use Fresh\Mvc\Model\Dao;
use Fresh\Weird\QueryBuilder;

class OrderDao extends Dao
{
    /**
     * @ConnectionField(name="dangkou")
     */
    public function getClientPayment($cids, $startDate = null, $endDate = null)
    {
        return $this->expr()
            ->from(ApiHupunTrades::class)
            ->whether(function (QueryBuilder $qb) use ($cids, $startDate, $endDate) {
                if (is_array($cids)) {
                    $qb->inWhere('cid', $cids);
                } else {
                    $qb->where('cid=?', $cids);
                }

                if ($startDate && $endDate) {
                    $qb->rangeDate2Datetime($startDate, $endDate, 'pay_time');
                }
            })
            ->query()
            ->pluck('sum(payment_discount)');
    }

    /**
     * @ConnectionField(name="dangkou")
     */
    public function getClientList($cids, $page, $limit, $startDate = null, $endDate = null)
    {
        $qb = $this->expr()
            ->field('
            c.(cid, client_name, realname, phone, is_agent), FROM_UNIXTIME(c.date, "%Y-%m-%d %H:%i:%S") date,
            IFNULL(sum(aht.payment_discount), 0) total_achieve
            ')
            ->from(Client::class, 'c')
            ->leftJoin(ApiHupunTrades::class, 'c.cid=aht.cid', 'aht')
            ->inWhere('c.cid', $cids)
            ->whether(function (QueryBuilder $qb) use ($startDate, $endDate) {
                if ($startDate && $endDate) {
                    $qb->rangeDate2Datetime($startDate, $endDate, 'aht.pay_time');
                }
            })
            ->groupBy('c.cid')
            ->orderBy('date desc');

        return $this->paginate($qb, $page, $limit);
    }
}
